<template>
  <div>
    <div v-show="false">{{ height }}{{ width }}{{ chartsValue }}{{ foreColor }}{{ timeInit }}</div>
    <div v-show="this.detail.dataBind.lData.length>0" :id="detail.identifier" ref="chartView" class="view-chart"
         @dblclick="dblclick"/>
    <div v-show="this.detail.dataBind.lData.length==0" :style="{
        width: this.detail.style.position.w + 'px',
        height: this.detail.style.position.h+'px',
        'text-align':'center',
        'line-height':this.detail.style.position.h+'px',
        'font-size':'30px',
        'color':'#368a42'
    }" @dblclick="dblclick">双击绑定变量
    </div>
    <el-dialog
        :close-on-click-modal="false"
        :visible.sync="dialogVisible"
        append-to-body
        title="变量绑定" width="30%">
      <div style="height:15vh;overflow: auto;">
        <el-checkbox-group v-model="checkList">
          <el-checkbox v-for="item in paramNameList"
                       :key="item.deviceImei+'_'+item.paramField+'_'+item.paramName"
                       :label="item.deviceImei+'_'+item.paramField+'_'+item.paramName">{{ item.paramName }}
          </el-checkbox>
        </el-checkbox-group>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">关 闭</el-button>
        <el-button type="primary" @click="handleClick">确 定</el-button>
      </span>
    </el-dialog>
  </div>

</template>

<script>

import BaseView from '../View';
import topoUtil from '@/views/zutai/components/topo/util/topo-util';
import request from "@/utils/request";

export default {
  name: 'ViewChart',
  extends: BaseView,
  props: {},
  computed: {
    width() {
      this.$nextTick(function () {
        this.myChart.resize({
          width: this.detail.style.position.w,
          height: this.detail.style.position.h
        });
      });
      return this.detail.style.position.w
    },
    height() {
      this.$nextTick(function () {
        this.myChart.resize({
          width: this.detail.style.position.w,
          height: this.detail.style.position.h
        });
      });
      return this.detail.style.position.h
    },
    chartsValue() {
      //将回调延迟到下次DOM更新循环之后执行。在修改数据之后立即使用它，然后等待DOM更新
      return this.detail.dataBind.paramValue;
    },
    foreColor() {
      this.$nextTick(function () {
        this.option.legend.textStyle.color = this.detail.style.foreColor;
        this.option.xAxis.axisLabel.textStyle.color = this.detail.style.foreColor;
        this.option.xAxis.axisLabel.interval = this.detail.dataBind.xInterval;
        this.option.yAxis.axisLabel.textStyle.color = this.detail.style.foreColor;
        this.setOption(this.option)
      });
      return this.detail.style.foreColor + this.detail.dataBind.xInterval;
    },
    timeInit() {
      this.getChartsData();
      return this.detail.dataBind.timeNum + this.detail.dataBind.timeInterval;
    }
  },
  data() {
    return {
      myChart: null,
      option: {
        title: {
          text: ''
        },
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          textStyle: {color: this.detail.style.foreColor},
          data: []
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        toolbox: {
          feature: {
            saveAsImage: {}
          }
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: [],
          axisLabel: {
            formatter: function (params) {
              let newParamsName = '';
              const paramsNameNumber = params.length;
              const provideNumber = 5; // 一行显示几个字 然后就超过字数就会自动换行
              const rowNumber = Math.ceil(paramsNameNumber / provideNumber);
              if (paramsNameNumber > provideNumber) {
                for (let p = 0; p < rowNumber; p += 1) {
                  let tempStr = '';
                  const start = p * provideNumber;
                  const end = start + provideNumber;
                  if (p === rowNumber - 1) {
                    tempStr = params.substring(start, paramsNameNumber);
                  } else {
                    tempStr = `${params.substring(start, end)}\n`;
                  }
                  newParamsName += tempStr;
                }
              } else {
                newParamsName = params;
              }
              newParamsName = newParamsName.substring(5, newParamsName.length)
              return newParamsName;
            },
            inside: false,
            interval: this.detail.dataBind.xInterval, // 强制文字产生间隔,为0时显示所有的点
            //rotate: 90, // 文字逆时针旋转45°
            textStyle: {
              color: this.detail.style.foreColor,
              // fontSize: 16,
              // itemSize: ''
            }
          },
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            textStyle: {
              color: this.detail.style.foreColor,
            }
          },
        },
        series: []
      },
      paramNameList: [],
      checkList: [],
      dialogVisible: false,
      timer: null,
    }
  },
  methods: {
    dblclick() {
      // console.log("双击绑定字段");
      this.dialogVisible = true;
      this.checkList = this.detail.dataBind.lData;
    },
    handleClick() {
      console.log("绑定的字段", this.checkList);
      this.dialogVisible = false;
      // this.detail.dataBind.imei =
      this.detail.dataBind.lData = this.checkList;
      this.getChartsData();
    },
    setOption(option) {
      this.myChart.setOption(option)
    },
    //获取设备变量
    getParam() {
      // let query={
      // pageNum: 1,
      // pageSize: 999,
      // deviceImei:this.$route.query.deviceImei,
      // orderByColumn:"id",
      // isAsc:"asc",
      // }
      // let url="/zutai/bDeviceRealData/list"
      // this.paramNameList=[];
      // request({
      // url:url,
      // method:"get",
      // params: query,

      // }).then((res)=>{
      //     console.log('设备参数!',res);
      //     if(res.code==200){
      //         res.rows.forEach(element => {
      //             this.paramNameList.push(element.paramName)
      //         });
      //     }
      // })

      let query = {
        pageNum: 1,
        pageSize: 999,
        ztGuid: this.$route.query.guid,
        orderByColumn: "id",
        isAsc: "desc",
      }
      let url = "/zutai/bDeviceRealData/getBindDatalist"
      this.paramNameList = [];
      request({
        url: url,
        method: "get",
        params: query,

      }).then((res) => {
        console.log('设备参数!', res);
        if (res.code == 200) {
          this.paramNameList = res.rows;
          /*res.rows.forEach(element => {
            if (element.paramName) {
              this.paramNameList.push(element.paramName)
            }
          });*/
        }
      })

    },
    getChartsData() {
      if (this.detail.dataBind.lData.length == 0) {
        // console.log("无绑定变量数据");
        return;
      }
      let timeNum = 2
      let timeInterval = 10
      if (this.detail.dataBind.timeNum) {
        timeNum = this.detail.dataBind.timeNum;
      }
      if (this.detail.dataBind.timeInterval) {
        timeInterval = this.detail.dataBind.timeInterval;
      }
      console.log(this.detail.dataBind);
      let query = {
        deviceImei: this.detail.dataBind.lData.map(c => c.split("_")[0]).join(';'),
        startTime: topoUtil.getTime(timeNum),
        endTime: topoUtil.getNowTime(),
        minute: timeInterval,
        paramFields: this.detail.dataBind.lData.map(c => c.split("_")[1]).join(';'),
        paramNames: this.detail.dataBind.lData.map(c => c.split("_")[2]).join(';'),
      }
      let url = "/zutai/bDeviceRealData/getVariableLines"
      request({
        url: url,
        method: "get",
        params: query,
      }).then((response) => {
        // console.log("获取统计数据",response);
        let ldata = [];
        let xdata = [];
        let ydata = [];
        if (response.data.timeList) {
          response.data.timeList.forEach(element => {
            // xdata.push(moment(element).format('HH:mm'))
            xdata.push(element)
          });
        }
        if (response.data.list) {
          response.data.list.forEach(element => {
            ldata.push(element.paramName)
            ydata.push(element)
          });
        }
        this.option.legend.data = ldata
        this.option.xAxis.data = xdata
        this.option.series = [];
        ydata.forEach(element => {
          let data = {};
          if (this.detail.type == 'chart-line') {
            data = {
              name: element.paramName,
              type: 'line',
              stack: 'Total',
              data: element.data,
              itemStyle: {},
            }
          } else if (this.detail.type == 'chart-line-step') {
            data = {
              name: element.paramName,
              type: 'line',
              stack: 'Total',
              step: 'start',
              data: element.data,
              itemStyle: {},
            }
          } else {
            data = {
              name: element.paramName,
              type: 'bar',
              stack: 'Total',//有代表是一个柱形图堆叠，无这属性柱形分散排列
              barWidth: 17,
              data: element.data,
              itemStyle: {},
            }
          }

          this.option.series.push(data)
        });
        this.$nextTick(function () {
          this.setOption(this.option);
        });
      })
    },
  },
  mounted() {
    this.myChart = this.$echarts.init(document.getElementById(this.detail.identifier));
    this.getParam()
    this.getChartsData();
    this.timer = setInterval(() => {
      this.getChartsData();
    }, 10000);
  },
  beforeDestroy() {
    clearInterval(this.timer)
    this.timer = null;
  },

}
</script>

<style lang="scss">
.view-chart {
  height: 100%;
  width: 100%;
  text-align: center;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
